import {router} from '#/router'
import {resetAllStores, useAccessStore, useUserStore} from '@vben/stores';
import {defineStore} from 'pinia';
import {getCaptchaImage, getUserInfoApi, getUserRouter, logoutApi, userLogin,} from '#/api';
import {message} from "ant-design-vue";


import {DEFAULT_HOME_PATH, LOGIN_PATH} from '@vben/constants'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    loginLoading: false,
    captcha: {
      image: '',
      uuid: '',
    },
  }),
  getters: {},
  actions: {
    async refreshCaptchaImage() {
      // 初始化验证码
      const {data: {img, uuid}} = await getCaptchaImage()
      this.captcha.image = `data:image/png;base64,${img}`;
      this.captcha.uuid = uuid;
    },
    async authLogin(params: Parameters<typeof userLogin>[0], onSuccess?: () => Promise<void> | void) {
      this.loginLoading = true;
      const {data: {token, code, msg}} = await userLogin(params);
      if (code === 200) {
        message.success({
          content: '恭喜你，登录成功',
        });
        const accessStore = useAccessStore();
        const userStore = useUserStore();
        accessStore.setAccessToken(token);

        // 获取用户信息及路由列表
        const [data1,data2] =await Promise.all([getUserInfoApi(),getUserRouter()])
        console.log("data1",data1)
        console.log("data2",data2)
        userStore.setUserInfo(data1)
        userStore.setUserRoles(data1.user.roles)
        // let userInfo = await this.fetchUserInfo()
        // accessStore.setAccessCodes(userInfo.roles);

        //获取用户路由列表


        console.log(DEFAULT_HOME_PATH)
        console.log(router)
        await router.push(DEFAULT_HOME_PATH)
      } else {
        message.error(msg);
        await this.refreshCaptchaImage()
      }
      console.log(onSuccess)


    },
    async logout(redirect: boolean = true) {
      try {
        await logoutApi();
      } catch {
      // 不做任何处理
      }
      resetAllStores();
      const accessStore = useAccessStore();
      accessStore.setLoginExpired(false);

      // 回登录页带上当前路由地址
      await router.replace({
        path: LOGIN_PATH,
        query: redirect
          ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
          : {},
      });
    },
    async fetchUserInfo() {
      const userStore = useUserStore();
      const data = await getUserInfoApi();
      userStore.setUserInfo(data);
      return data;
    },
    $reset() {
      this.loginLoading = true;
    }
  },

})
